package com.qk.mangement.web.interceptor;


import com.qk.common.util.CurrentUserHolder;
import com.qk.common.util.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.Optional;

 @Component
 @Slf4j
 public class TokenInterceptor implements HandlerInterceptor {
     private static final String TOKEN_HEADER_NAME = "token";
     @Override
     public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
         String token = request.getHeader(TOKEN_HEADER_NAME);
         Optional<String> optional = Optional.ofNullable(token);
         if (!optional.isPresent()){
             response.setStatus(HttpStatus.UNAUTHORIZED.value());
             return false;
         }

         try {
             log.info("interceptor开始解析令牌");
             Claims claims = JwtUtils.parseToken(token);
             //解析token,获取用户id,存入threadLocal
             Integer userId = claims.get("id", Integer.class);
             log.info("解析令牌成功, 获取用户id: {}", userId);
             CurrentUserHolder.setCurrentUserId(userId);
             return true;
         } catch (Exception e) {
             e.printStackTrace();
             log.info("解析令牌失败, 返回错误结果");
             response.setStatus(HttpStatus.UNAUTHORIZED.value());
             return false;
         }
     }

     @Override
     public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
         //请求结束,删除用户id
         CurrentUserHolder.removeCurrentUserId();
     }

}
